<?php

class Core_Model_Subject_Category extends Dcmp_Model_Entity {

    public function __construct() {
        parent::__construct();
    }

    protected function getTableClass() {
        return Kd_Loader::loadClass('table_subject_category');
    }

    protected function beforeInsert($transaction) {
        $sefurl = $this->getSefUrl();
        if (empty($sefurl)) {
            $this->setSefUrl('/subject/' . $this->getTitle());
        }

        $parent = new self();
        if ($this->getParentId()) {
            $idPath = $parent->load($this->getParentId())->getIdPath();
            $this->setIdPath($idPath);
        } else {
            $this->setParentId(0);
            $this->setIdPath('');
        }
        parent::beforeInsert($transaction);
    }

    protected function afterInsert($transaction) {
        $this->getTable()->insertIdPath($this->getId(), $this->getIdPath() . $this->getId() . '_', $transaction);
        if ($this->issetData('sef_url')) {
            App::getHelper('website')->addSefUrl('subject_category', $this->getId(), '/subject/category/id/' . $this->getId(), $this->getSefUrl());
        }

        parent::afterInsert($transaction);
    }

    protected function beforeUpdate($transaction) {
        if ($this->propertyIsChanged('parent_id')) {
            $parent = new self();
            if ($this->getParentId()) {
                $idPath = $parent->load($this->getParentId())->getIdPath() . $this->getId() . '_';
                $this->setIdPath($idPath);
            } else {
                $this->setParentId(0);
                $this->setIdPath($this->getId() . '_');
            }
        }
        parent::beforeUpdate($transaction);
    }

    protected function afterUpdate($transaction) {
        if ($this->propertyIsChanged('sef_url')) {
            App::getHelper('website')->deleteSefUrl('subject_category', $this->getId(), $transaction);
            if($this->issetData('sef_url')){
                App::getHelper('website')->addSefUrl('subject_category', $this->getId(), '/subject/category/id/' . $this->getId(), $this->getSefUrl());
            }
        }
        if ($this->propertyIsChanged('parent_id')) {
            $this->getTable()->updateIdPath($this->getOriginalData('id_path'), $this->getIdPath(), $transaction);
        }
        parent::afterUpdate($transaction);
    }

    protected function initializeTable($table) {
        $table->setName('{t}subject_category');
        $table->createColumn('id', 'integer', TRUE, TRUE);
        $table->createColumn('name', 'string');
        $table->createColumn('sef_url', 'string');
        $table->createColumn('theme_id', 'guid')->setDefaultValue(0);
        $table->createColumn('parent_id', 'integer')->setDefaultValue(0);
        $table->createColumn('id_path', 'string');
    }
}